//
// Created by vans on 16-11-28.
//

/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
/*
 * libusb example program for hotplug API
 * Copyright © 2012-2013 Nathan Hjelm <hjelmn@mac.ccom>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <stdio.h>

#include "libusb.h"

//int done = 0;
//libusb_device_handle *handle = NULL;
static int bExit = 0;
static void send_event(char *action,int vid, int pid);
//
// Created by vans on 16-11-29.
//

#include <Python.h>

static void getcurrent(void)
{
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('.')");
    PyRun_SimpleString("sys.path.append('./flaskr')");
    PyRun_SimpleString("sys.path.append('./flaskr/poll')");
    return;
}

static void send_event(char *action,int vid, int pid)
{
    printf("send_event a\n");
    Py_Initialize();//初始化python
    if ( !Py_IsInitialized() ) {
        printf("pyinit fail");
        return;
    }
    getcurrent();
    printf("send_event b\n");
    PyObject *pModule = NULL, *pFunc = NULL, *pArg = NULL;
    pModule = PyImport_ImportModule("usb_callback");//引入模块
    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, "handle_hotplug");//直接获取模块中的函数
        printf("send_event c\n");
        pArg = Py_BuildValue("(sii)", action,vid,pid); //参数类型转换，传递一个字符串。将c/c++类型的字符串转换为python类型，元组中的python类型查看python文档
        printf("send_event e\n");
        PyEval_CallObject(pFunc, pArg); //调用直接获得的函数，并传递参数
    }
    else
    {
        printf("pmodulenull\n");
    }
    Py_Finalize(); //释放python
    return;
}

static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
{
    struct libusb_device_descriptor desc;
    int rc;

    rc = libusb_get_device_descriptor(dev, &desc);
    if (LIBUSB_SUCCESS != rc) {
        fprintf (stderr, "Error getting device descriptor\n");
    }
    printf ("2Device attached: %04x:%04x\n", desc.idVendor, desc.idProduct);
    send_event("add",desc.idVendor,desc.idProduct);
    return 0;
}

static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
{
    struct libusb_device_descriptor desc;
    int rc;

    rc = libusb_get_device_descriptor(dev, &desc);
    if (LIBUSB_SUCCESS != rc) {
    fprintf (stderr, "Error getting device descriptor\n");
    }

    printf ("Device dettached: %04x:%04x\n", desc.idVendor, desc.idProduct);
    send_event("remove",desc.idVendor,desc.idProduct);
    return 0;
}

//void get_dev_info()
//{
//    FILE *fp = fopen("/proc/mount",'r");
//}

int stop_monitor_hotplug(void)
{
    bExit = 1;
    return 0;
}

int start_monitor_hotplug(void)
{
    libusb_hotplug_callback_handle hp[2];
    int product_id, vendor_id, class_id;
    int rc;

    vendor_id  =  LIBUSB_HOTPLUG_MATCH_ANY;
    product_id =  LIBUSB_HOTPLUG_MATCH_ANY;
    class_id   =  LIBUSB_HOTPLUG_MATCH_ANY;

    rc = libusb_init (NULL);
    if (rc < 0)
    {
        printf("failed to initialise libusb: %s\n", libusb_error_name(rc));
        return EXIT_FAILURE;
    }

    if (!libusb_has_capability (LIBUSB_CAP_HAS_HOTPLUG)) {
        printf ("Hotplug capabilites are not supported on this platform\n");
        libusb_exit (NULL);
        return EXIT_FAILURE;
    }
    else
    {
        printf("support hotplug\n");
    }

    rc = libusb_hotplug_register_callback (NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, 0, vendor_id,
                                           product_id, class_id, hotplug_callback, NULL, &hp[0]);

    if (LIBUSB_SUCCESS != rc) {
        fprintf (stderr, "Error registering callback 0\n");
        libusb_exit (NULL);
        return EXIT_FAILURE;
    }

    rc = libusb_hotplug_register_callback (NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, vendor_id,
                                           product_id,class_id, hotplug_callback_detach, NULL, &hp[1]);
    if (LIBUSB_SUCCESS != rc) {
        fprintf (stderr, "Error registering callback 1\n");
        libusb_exit (NULL);
        return EXIT_FAILURE;
    }

    while (!bExit) {
        rc = libusb_handle_events (NULL);
        if (rc < 0)
        {
            printf("libusb_handle_events() failed: %s\n", libusb_error_name(rc));
        }
    }

    libusb_exit (NULL);
    return EXIT_SUCCESS;
}
